//
//  LookBigPictureController.m
//  图片浏览器
//
//  Created by zxy on 2018/10/22.
//  Copyright © 2018年 zxy. All rights reserved.
//

#import "LookBigPictureController.h"

@interface LookBigPictureController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrolView;
@property(nonatomic,strong)UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@end

@implementation LookBigPictureController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCtl];
}

-(void)setupCtl{
    NSString *pic = [self.model.cover componentsSeparatedByString:@"?"][0];
    //图片宽高比，正常服务器模型要返回宽高比
    CGFloat p = 800.0 / 450;
    CGFloat imgH = screenWidth / p;
    UIImageView *imgView = [[UIImageView alloc]init];
    [imgView sd_setImageWithURL:[NSURL URLWithString:pic] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if(!image){
            [SVProgressHUD showErrorWithStatus:@"图片获取失败"];
        }else{//图片完全加载成功，才能让保存按钮能点击
            self.saveBtn.enabled = YES;
        }
    }];
    imgView.xmg_width = self.scrolView.xmg_width;
    imgView.xmg_height = imgH;
    imgView.xmg_x = 0;
    if(imgH > screenHeight){
        imgView.xmg_y = 0;
        self.scrolView.contentSize = CGSizeMake(0, imgH);
    }else{//图片居中
        imgView.xmg_centerY = screenHeight * 0.5;
    }
    [self.scrolView addSubview:imgView];
    self.iconImageView = imgView;
    
    //控制缩放
//    CGFloat maxScale = 图片实际宽度 / screenWidth;
//    if(maxScale > 1){
//          self.scrolView.delegate = self;
//        self.scrolView.maximumZoomScale = maxScale;
//    }
    self.scrolView.maximumZoomScale = 1.5;//正常要获取图片实际宽度，在做设置，不然这样直接设置放大图片，会下移动
    
    //添加手势，点击空白区域让控制器推出
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [self.scrolView addGestureRecognizer:tap];
}
- (IBAction)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -保存图片到相册
- (IBAction)save:(UIButton *)sender {
    UIImageWriteToSavedPhotosAlbum(self.iconImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if(error){
        [SVProgressHUD showErrorWithStatus:@"图片保存失败"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"图片保存成功"];
    }
}

//返回要缩放的view
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.iconImageView;
}
@end
